const {
deleteData,
page,
list,
newsData,
option,
} = require("../../api/index.js")
const utils = require("../../utils/index.js")
Page({
/**
* 页面的初始数据
*/
data: {

	sortType:'',
	sortOrder:'',
        questList: [],
    pageNum: 1,
pageSize: 10,
    total: 0,
    flag: true, // 防抖开关 防止用户不停的下拉


popopShow:false,

chengguofenleiOptions:[],
showToTopButton: true,
onPageScrollTop: 0, // 存储滚动距离的变量
goodsListData: [],
activeIndex: 0,
allData: [],
deleteShow: false,
className:"",
name:"",
addAuth:"",
delAuth: "",
editAuth:"" ,
        silderList:[],
                                                                                                        userid:"",
baseURL: wx.getStorageSync('baseURL') + "/",
isAuthStatus:false
},

/**
* 生命周期函数--监听页面加载
*/
async onLoad(options) {
this.setData({
        isAuthStatus: wx.getStorageSync('isAuth'),
        userid:wx.getStorageSync('userid')
})
if(options?.userid) {
this.setData({
    userid:options.userid
})

}
const currentPageUrl = this.getCurrentPageUrl();
if(getApp().globalData.name!=null){
this.setData({
    name: getApp().globalData.name
})
getApp().globalData.name=null
this.searhandler()
}

 let obj = {};
//chengguofenlei筛选
let resInfochengguofenlei = await option('chengguofenlei/chengguofenlei')
    obj["chengguofenleiOptions"]= resInfochengguofenlei.data
this.setData({
    ...obj
})
if (currentPageUrl == "/pages/xiangmuchengguo/list") {
    wx.setStorageSync("tableName",`xiangmuchengguo`)
    this.setData({
        className:"goodInfomation"
    })
}else {
    this.setData({
        className:"other"
    })

}

},

onShow() {
// 优先恢复全局变量中的筛选条件和结果
const filter = getApp().globalData.xmcgFilter;
if (filter) {
  this.setData({
    chengguofenlei: filter.chengguofenlei,
    chengguomingcheng: filter.chengguomingcheng,
    sortType: filter.sortType,
    sortOrder: filter.sortOrder,
    goodsListData: filter.goodsListData
  });
  // 恢复后清空全局缓存，避免下次误用
  getApp().globalData.xmcgFilter = null;
  return;
}
this.setData({
sortType: ""
})
// 获取当前页面栈
const pages = getCurrentPages();
// 获取当前页面对象
const currentPage = pages[pages.length - 1];
// 获取当前页面的显示报告对象
let displayReporter = currentPage.__displayReporter;
if (getApp().globalData.name == null) {
    this.setData({
        name: null
    })
    this.setData({
        isAuthStatus: wx.getStorageSync('isAuth')
    })
    }
const currentPageUrl = this.getCurrentPageUrl();
if(getApp().globalData.name){
    this.setData({
        name: getApp().globalData.name
    })
    getApp().globalData.name=null
    this.searhandler()
}
this.setData({pageNum:1,goodsListData:[]})
this.getData()

},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onPageShow() {
// 页面显示时执行的操作
},
sortClick (e){
  const type=  e.currentTarget.dataset.info;
	if(this.data.sortType==type && this.data.sortOrder=='asc'){
        this.setData({sortType:''})

	}else if(this.data.sortType==type && this.data.sortOrder=='desc'){
		 this.setData({sortOrder:'asc'})
	}else{
		this.setData({sortType:type,sortOrder:'desc'})
	}
	this.search()
},

chengguofenleiChange(e) {
  const category = e.currentTarget.dataset.item;
  this.setData({
    chengguofenlei: category
  });
  // 分类筛选逻辑
  if (!category) {
    // 全部，显示所有
    this.setData({
      goodsListData: this.data.allData
    });
  } else {
    // 只显示该分类
    this.setData({
      goodsListData: this.data.allData.filter(item => item.chengguofenlei === category)
    });
  }
},





screenReset(){
    let obj={}
//chengguofenlei
obj["chengguofenlei"]=""
// 清空全局变量缓存
getApp().globalData.xmcgFilter = null;
    this.setData(obj)

},



async   search(){
const nowTable=wx.getStorageSync('nowTable')
let searchForm = {
page: 1,
limit: 999,
 sfsh: "是"
}


if(this.data.sortType){
searchForm['sort'] = this.data.sortType;
searchForm['order'] = this.data.sortOrder;
}
if(this.data.chengguomingcheng){
    searchForm['chengguomingcheng'] = '%' + this.data.chengguomingcheng + '%'
}
if(this.data.chengguofenlei){
    searchForm['chengguofenlei'] ='%' +  this.data.chengguofenlei + '%'
}

let user = wx.getStorageSync("userid")?wx.getStorageSync('userSession'):{};
if(user.chengshi){
searchForm['chengshi'] = user.chengshi
}
if(user.xianqu){
searchForm['xianqu'] = user.xianqu
}
if(user.jiedao){
searchForm['jiedao'] = user.jiedao
}
if(user.xuexiaomingcheng){
searchForm['xuexiaomingcheng'] = user.xuexiaomingcheng
}
if(user.xueyuanmingcheng){
searchForm['xueyuanmingcheng'] = user.xueyuanmingcheng
}
let res = {};
if( this.data.isAuthStatus) {
   
res = await page(`xiangmuchengguo`, searchForm);
} else {
res = await list(`xiangmuchengguo`, searchForm);
}


let goodsListData
// 如果是第一页数据置空
 if ( this.data.pageNum == 1) {
     goodsListData = []
 };
if(res.code==0){
    goodsListData=res.data.list.map(item=>{
        item.tupian.indexOf('http') !== -1?item.tupian: item.tupian = this.data.baseURL+item.tupian?.split(",")[0].replace('upload','flie')
        return item
    });
    // 前端分类筛选
    if (this.data.chengguofenlei) {
      goodsListData = goodsListData.filter(item => item.chengguofenlei === this.data.chengguofenlei);
    }
    this.setData({
      goodsListData: goodsListData,
      popopShow:false
    })
}



},
/**
* 生命周期函数--监听页面显示
*/
getCurrentPageUrl() {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const currentPageUrl = `/${currentPage.route}`;
return currentPageUrl;
},
async  handleTabClick(e) {
        let params={
         sfsh: "是"
        }
        const nowTable=  wx.getStorageSync('nowTable')
        const index = e.currentTarget.dataset.index;

let chengguofenlei= e.currentTarget.dataset.chengguofenlei;
chengguofenlei=='全部'?'':params["chengguofenlei"]='%'+chengguofenlei+'%';
let res={};
    if( this.data.isAuthStatus){
        res=await page(`xiangmuchengguo`,params);
    }else{
        res =await list(`xiangmuchengguo`,params);
    }
let goodsListData=res.data.list.map(item => {
if(item.tupian.includes('https')){
item.tupian=item.tupian.split(',')[0]
}else{
item.tupian=this.data.baseURL+item.tupian.split(',')[0];
}
return item
}
)

    this.setData({
        activeIndex:index,
        goodsListData:   goodsListData     })
                                                                                                        },
    async searhandler(){
        let token = wx.getStorageSync('token')
        if (!token) {
            return
        }
let targetName="chengguomingcheng"
        const allData=this.data.allData

        let goodsListData

        if(this.data.name==''){
            goodsListData=allData
        }else{
            goodsListData = allData.filter(item => item[targetName].includes(this.data.name));

        }

        this.setData({
            goodsListData  : goodsListData        })



    },
screenBoxShow() {
this.setData({
    popopShow: true
})
},
addTap() {
// 保存筛选条件和结果到全局变量
getApp().globalData.xmcgFilter = {
  chengguofenlei: this.data.chengguofenlei,
  chengguomingcheng: this.data.chengguomingcheng,
  sortType: this.data.sortType,
  sortOrder: this.data.sortOrder,
  goodsListData: this.data.goodsListData
};
getApp().globalData.detailId=null
wx.navigateTo({
url: `/pages/xiangmuchengguo/update-and-add`
})
if(this.data.isAuthStatus) {
setTimeout(function () {
    wx.setStorageSync('isAuth', true)
}, 1000)
}
},
searchListHandler(e) {
this.setData({
goodsListData: e.detail.data
})
},
onPageScroll(e) {
if (e.scrollTop >= 225) {
this.setData({
    showToTopButton: true
});
}

},
backToTop() {
wx.pageScrollTo({
scrollTop: 0, // 返回顶部的位置
duration: 1000, // 滚动动画的时长，单位为 ms
});
// 返回顶部时隐藏按钮

},
deleteBtn(e) {
wx.showModal({
title: '提示',
content: '确认删除？',
complete: async (res) => {
    if (res.cancel) {}
    if (res.confirm) {
        const id = e.currentTarget.dataset.id;
        const res = await deleteData("xiangmuchengguo",[id])
        console.log(res);
        if (res.code == 0) {
            this.onShow()
        }
    }
}
})
},
editBtn(e) {
const item = e.currentTarget.dataset.item;
if(item?.id){
// 保存筛选条件和结果到全局变量
getApp().globalData.xmcgFilter = {
  chengguofenlei: this.data.chengguofenlei,
  chengguomingcheng: this.data.chengguomingcheng,
  sortType: this.data.sortType,
  sortOrder: this.data.sortOrder,
  goodsListData: this.data.goodsListData
};
getApp().globalData.detailList =item;
getApp().globalData.detailId=item.id;
wx.navigateTo({
url: `/pages/xiangmuchengguo/update-and-add?id=${item.id}&isAuth=${this.data.isAuthStatus}`
})
if(this.data.isAuthStatus) {
setTimeout(function () {
wx.setStorageSync('isAuth', true)
}, 1000)
}
}
},
async detailBtn(e) {
const item = e.currentTarget.dataset.item;
if(item?.id){
// 保存筛选条件和结果到全局变量
getApp().globalData.xmcgFilter = {
  chengguofenlei: this.data.chengguofenlei,
  chengguomingcheng: this.data.chengguomingcheng,
  sortType: this.data.sortType,
  sortOrder: this.data.sortOrder,
  goodsListData: this.data.goodsListData
};
getApp().globalData.detailId = item.id;
getApp().globalData.detailList =item
wx.navigateTo({
url: `/pages/xiangmuchengguo/detail?isAuth=${this.data.isAuthStatus}`
})
if(this.data.isAuthStatus) {
setTimeout(function () {
wx.setStorageSync('isAuth', true)
}, 1000)
}
    }

},
     /**
      * 页面上拉触底事件的处理函数
      */
onReachBottom() {

         if (this.data.flag ) {
             this.setData({
                 flag: false
             })
             this.getData(); // 疯狂的请求的方法
         }
     },
async getData() {
    const obj={
        page: 1,
        limit: 9999, // 一次性请求所有数据
        sfsh: "是"
    }
    const nowTable=wx.getStorageSync('nowTable')
    const userId= getApp().globalData.userInfo.id
    let isAuthObj={}
    if(this.data.isAuthStatus){
        isAuthObj['addAuth']   = utils.isAuth("xiangmuchengguo", "新增")
        isAuthObj['delAuth']  = utils.isAuth("xiangmuchengguo", "删除")
        isAuthObj['editAuth']   =utils.isAuth("xiangmuchengguo", "修改")
    }else{
        isAuthObj['addAuth']   = utils.isAuthFront("xiangmuchengguo", "新增")
        isAuthObj['delAuth']  = utils.isAuthFront("xiangmuchengguo", "删除")
        isAuthObj['editAuth']   =utils.isAuthFront("xiangmuchengguo", "修改")
    }
    this.setData(isAuthObj)

    let resList
    let user = wx.getStorageSync("userid")?wx.getStorageSync('userSession'):{};
    if(user.chengshi){
        obj['chengshi'] = user.chengshi
    }
    if(user.xianqu){
        obj['xianqu'] = user.xianqu
    }
    if(user.jiedao){
        obj['jiedao'] = user.jiedao
    }
    if(user.xuexiaomingcheng){
        obj['xuexiaomingcheng'] = user.xuexiaomingcheng
    }
    if(user.xueyuanmingcheng){
        obj['xueyuanmingcheng'] = user.xueyuanmingcheng
    }
    if(this.data.isAuthStatus){
        resList = await page("xiangmuchengguo",obj)
    }else{
        resList= await list("xiangmuchengguo",obj)
    }
    if(resList.code==0){
      let allData = resList.data.list.map(item => {
        item.tupian?.indexOf('http') !== -1
          ? item.tupian
          : item.tupian = this.data.baseURL + item.tupian?.split(",")[0].replace('upload','flie');
        return item;
      });
      this.setData({
        goodsListData: allData,
        allData: allData
      });
    }

    // 商品名称
    if (getApp().globalData.name != null) {
      this.setData({
        goodsListData:  getApp().globalData.goodsList ,
      })
      getApp().globalData.name = null
      console.log('页面重新加载');
    }

    const arr = [{
        chengguofenlei: "全部"
    }]

    const chengguofenleiobj={
      page:1,
      limit:100
    }
    let    chengguofenleiRes
    //侧边栏
    if(userId){
      chengguofenleiRes = await page('chengguofenlei',chengguofenleiobj)
    }else{
      chengguofenleiRes = await list('chengguofenlei',chengguofenleiobj)
    }
    arr.push(...chengguofenleiRes.data.list)
    this.setData({
      silderList:arr
    })
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
    wx.removeStorageSync('isAuth');
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {

},

/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {

},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {

},
closePopup() {
  this.setData({ popopShow: false });
},
confirmCategoryFilter() {
  this.setData({ popopShow: false });
  this.search();
},
search() {
  let { allData, chengguofenlei, chengguomingcheng, sortType, sortOrder } = this.data;
  let result = allData || [];

  // 分类筛选
  if (chengguofenlei) {
    result = result.filter(item => item.chengguofenlei === chengguofenlei);
  }

  // 名称模糊搜索
  if (chengguomingcheng) {
    result = result.filter(item => item.chengguomingcheng && item.chengguomingcheng.indexOf(chengguomingcheng) !== -1);
  }

  // 本地排序
  if (sortType) {
    result = result.slice().sort((a, b) => {
      let aVal = Number(a[sortType]) || 0;
      let bVal = Number(b[sortType]) || 0;
      if (sortOrder === 'asc') {
        return aVal - bVal;
      } else {
        return bVal - aVal;
      }
    });
  }

  this.setData({
    goodsListData: result
  });
},
onInputChange(e) {
  this.setData({
    chengguomingcheng: e.detail.value
  });
},
})
